<template>
  <div class="details" id="basic-demo">
    <div class="returngo" @click="runturgo"><icon-undo /> 返回</div>
    <div class="primary" v-if="showButton" @click="primarytop">
      <icon-to-top />
    </div>
    <div class="spinnu" v-if="aspindot">
      <a-spin dot />
    </div>

    <div class="spinnu" v-if="pfdspin">
      <a-spin dot tip="正在下载pdf" />
    </div>
    <div class="imgdetails">
      <!-- <a-back-top
            target-container="#basic-demo"
            :style="{ position: 'absolute', bottom: '20px', right: '20px' }"
          /> -->

      <p class="details-p">
        <span style="font-size: 20px">{{ info.SaveName }}</span>
        <br />
        <span>编号：{{ info.singleCode }}</span>
        <span>测评时间：{{ info.AddTime }}</span> <br />
        姓名：{{ info.ClassName }}
      </p>
      <div class="details-img">
        <img :src="info.qrcodeTeacher" v-if="info.qrcodeTeacher" alt="" />
      </div>
      <p class="details-p">请微信联系指导老师</p>

      <div class="content-area" id="contentToConvert">
        <!-- <div> 测评概况</div> / -->

        <div class="content-detsils2">
          <Details1
            v-if="table1.length > 0"
            :table1="table1"
            :rotesData="rotesData"
            :typesArray="typesArray"
            :scoresArray="scoresArray"
            :avgSubRotes="avgSubRotes"
            :avgTates="avgTates"
          ></Details1>
        </div>
        <div class="content-detsils2">
          <Details2 v-if="klScoreLevdata" :klScoreLev="klScoreLevdata" />
        </div>
        <div class="content-detsils2">
          <Details3 v-if="skillLev" :skillLev="skillLev" />
        </div>
        <div class="content-detsils2">
          <Details4 v-if="capacityLev" :capacityLev="capacityLev" />
        </div>
        <div class="content-detsils2">
          <Details5
            v-if="knowledgeName.length > 0"
            :knowledgeName="knowledgeName"
            :info="info"
            :rates="rates"
            :brknowledgesName="brknowledgesName"
          />
        </div>
        <div class="content-detsils2">
          <Details6 v-if="klScoreLevdata" :klScoreLevdata="klScoreLevdata" />
        </div>
        <div class="content-detsils2">
          <Details7 v-if="monopolize" :monopolize="monopolize" />
        </div>
        <div class="content-detsils2">
          <Details8 v-if="monopolize1" :monopolize="monopolize1" />
        </div>
      </div>

      <div class="bottomlist">
        温馨提示：另有配套《课后自适应训练》内含三大板块①经典母题②实战演练③错题再现，帮助考生举一反三，实现从“学过”到“学会”的转变！
      </div>
      <!-- <button @click="downloadPdf">下载 PDF</button> -->
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, watch, nextTick } from "vue";
import { MyHomeworkhtmltopdf, postReportgetData } from "@/api/diagnosis";
import Details1 from "./center/details1.vue";
import Details3 from "./center/details3.vue";
import Details4 from "./center/details4.vue";
import Details5 from "./center/details5.vue";
import Details6 from "./center/details6.vue";
import Details7 from "./center/details7.vue";
import Details8 from "./center/details8.vue";
import Details2 from "./center/details2.vue";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import * as echarts from "echarts/core";
import useUserStore from "@/store/modules/user";
import { useRouter, useRoute } from "vue-router";
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const aspindot = ref(false);
// const receivedData = route.query.VID;
const subjectID = userStore.$state.subjectID;
const permission = JSON.parse(localStorage.getItem("permission") as any);
const downloadPdf = async () => {
  const pdf = new jsPDF();
  const componentContainers = document.querySelectorAll(".content-detsils2");

  for (let i = 0; i < componentContainers.length; i++) {
    const container = componentContainers[i] as HTMLElement;
    try {
      const options = {
        scale: 1,
        useCORS: true,
        allowTaint: true,
        scrollY: 0,
        height: container.scrollHeight,
        windowHeight: container.scrollHeight,
      };

      const canvas = await html2canvas(container, options);
      const imgData = canvas.toDataURL("image/png");
      const imgProps = pdf.getImageProperties(imgData);
      const pdfWidth = pdf.internal.pageSize.getWidth() - 20;
      const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

      // 计算需要多少页
      const pageHeight = pdf.internal.pageSize.getHeight() - 20;
      const totalPages = Math.ceil(pdfHeight / pageHeight);

      for (let p = 0; p < totalPages; p++) {
        if (p > 0 || i > 0) {
          pdf.addPage();
        }

        const position = p * pageHeight;
        pdf.addImage(imgData, "PNG", 10, 10 - position, pdfWidth, pdfHeight);
      }
    } catch (error) {
      console.error(`转换第 ${i + 1} 个组件为图片时出错:`, error);
    }
  }

  pdf.save("downloaded.pdf");
};

const table1 = ref([]);
const knowledgeName = ref([]);
const typesArray = ref();
const scoresArray = ref();
const rates = ref();
const brknowledgesName = ref();
const monopolize = ref();
const monopolize1 = ref();
const formname = reactive({
  gid: 0, //年级
  sid: 0, //学科
  paperID: 0, //试卷
  ctrID: 0, //
});
// query: {
//   SubjectID: e.SubjectID ,
//   CTRID: e.CTRID,
//   SaveID:e.SaveID,
// },
const rotesData = reactive({
  rotes: 0,
  totle: 0,
});

const klScoreLevdata = ref();
const skillLev = ref();
const capacityLev = ref();
const avgSubRotes = ref();
const info = reactive({
  SaveName: "",
  singleCode: "",
  AddTime: "",
  ClassName: "", //学生名
  OrganName: "", //学校名
  DocDiff: 0, //难度
  qrcodeTeacher: "",
});
// avgTates:[], //常模得分率
//   rotes:''//我的得分率
// info.avgTates = datalist.avgTates
//     info.rotes =datalist.rotes
const avgTates = ref();
const Report = () => {
  aspindot.value = true;
  // route.query.SubjectID
  formname.gid = permission.GradeID;
  formname.ctrID = route.query.CTRID;
  formname.sid = route.query.SubjectID;
  formname.paperID = route.query.SaveID;
  // route.query.SaveID
  postReportgetData(formname).then((res: any) => {
    const datalist = res[1].list;
    const infodata = datalist.info[0];
    info.SaveName = infodata.SaveName;
    info.singleCode = infodata.singleCode;
    info.AddTime = infodata.AddTime;
    info.ClassName = infodata.ClassName;
    info.OrganName = infodata.OrganName;
    info.DocDiff = infodata.DocDiff;
    info.qrcodeTeacher = infodata.qrcodeTeacher;
    avgTates.value = [datalist.avgTates, datalist.rotes];

    table1.value = Object.values(datalist.testInfo);
    knowledgeName.value = Object.values(datalist.knowledgeName).map(
      (item: any) => ({
        name: item[0], // 取 name（第 1 个元素）
        value: parseInt(item[1]), // 取 value（第 3 个元素，转为数字）
      })
    );
    rotesData.rotes = (datalist.rotes / datalist.totle) * 100;
    rotesData.totle = datalist.totle;
    // Object.values(datalist.testInfo)
    typesArray.value = Object.values(datalist.testInfo).map(
      (item: any) => item.TypesName
    );
    scoresArray.value = Object.values(datalist.testInfo).map(
      (item: any) => item.getScoreRates
    );
    // datalist.rates

    rates.value = datalist.rates.map((item: any) => item.rates);
    brknowledgesName.value = datalist.rates.map(
      (item: any) => item.brknowledgesName
    );
    // 专属1v1
    const exclusive = Object.values(datalist.jiqiaoVideo);
    const exclusive1 = Object.values(datalist.zxVideo);
    monopolize.value = exclusive;
    monopolize1.value = exclusive1;
    klScoreLevdata.value = JSON.parse(datalist.klScoreLev);
    skillLev.value = JSON.parse(datalist.skillLev);
    capacityLev.value = JSON.parse(datalist.capacityLev);
    // monopolize1.value= exclusive[1]
    avgSubRotes.value = parseInt(
      ((datalist.avgTates - datalist.rotes) / 100) *
        parseInt((datalist.totle / datalist.rotes) * 100)
    );
    aspindot.value = false;
    // if (res.buffer.rotes == 0) {
    //   $(".promote").html(res.buffer.avgTates);
    // } else if (res.buffer.rotes < res.buffer.avgTates) {
    //   //得分和常模比较接近时，小于5分的按照5分计算，大于5分的依旧按照常模-得分计算
    //   if (avgSubRotes >= 5) {
    //     $(".promote").html(avgSubRotes);
    //   } else {
    //     $(".promote").html(5);
    //   }
    // } else {
    //   $(".promote").html(
    //     parseInt(
    //       (1 - res.buffer.rotes / 100) *
    //         parseInt((res.buffer.totle / res.buffer.rotes) * 100)
    //     )
    //   );
    // }

    sendPageDataToBackend();
  });
};
import { Message } from "@arco-design/web-vue";
// 新函数：将页面数据发送给后端
const pfdspin = ref(false);
// 新函数：将页面数据及样式发送给后端
const sendPageDataToBackend = async () => {
  await nextTick(); // 等待DOM更新
  pfdspin.value = true;
  try {
    const imgdetailsElement = document.querySelector(".imgdetails");
    if (!imgdetailsElement) {
      console.error("未找到.imgdetails元素");
      pfdspin.value = false;
      return;
    }

    // 1. 获取所有样式（包括主页面和子页面）
    const styles = await Promise.all(
      Array.from(
        document.querySelectorAll('style, link[rel="stylesheet"]')
      ).map(async (styleElement) => {
        if (styleElement.tagName === "STYLE") {
          return styleElement.innerHTML;
        } else {
          try {
            const response = await fetch(styleElement.href);
            if (response.ok) {
              return await response.text();
            }
          } catch (error) {
            console.error(
              `Failed to fetch external CSS: ${styleElement.href}`,
              error
            );
          }
          return "";
        }
      })
    );
    const finalStyles = styles.join("\n");

    // 2. 处理图片 http://manfenbeikao.com/Public/newAat/images/default.png
    // const imgElements = imgdetailsElement.querySelectorAll("img");
    // for (const img of imgElements) {
    //   const src = img.src;
    //   if (src) {
    //     const response = await fetch(src);
    //     const blob = await response.blob();
    //     const reader = new FileReader();
    //     reader.readAsDataURL(blob);
    //     await new Promise((resolve) => {
    //       reader.onloadend = () => {
    //         img.src = reader.result;
    //         resolve();
    //       };
    //     });
    //   }
    // }
    // 假设 imgdetailsElement 已经定义
    const imgElements = imgdetailsElement.querySelectorAll("img");
    const baseUrl = "http://123.57.81.131:8081/";

    for (const img of imgElements) {
      let src = img.src;
      // 检查 src 是否已经是完整的 URL，如果不是则添加前缀
      if (!src.startsWith("http")) {
        src = baseUrl + src;
      }
      img.src = src;
    }

    // 检查 echarts 是否正确引入
    if (typeof echarts === "undefined") {
      console.error("ECharts 库未正确引入");
      return;
    }

    // 处理 ECharts 图表
    const echartsElements = imgdetailsElement.querySelectorAll(".echarts");
    for (const echartsElement of echartsElements) {
      const myChart = echarts.getInstanceByDom(echartsElement);
      if (myChart) {
        const svgData = myChart.getDataURL({ type: "svg" });
        if (!svgData.startsWith("data:image/svg+xml;charset=UTF-8,")) {
          // 这里可以添加一些处理逻辑，比如尝试重新获取，或者根据实际情况调整后续代码
          return;
        }

        // 提取 SVG 数据
        const rawSvgData = svgData.replace(
          "data:image/svg+xml;charset=UTF-8,",
          ""
        );
        const decodedSvg = decodeURIComponent(rawSvgData);

        // 创建一个新的 div 来包裹 SVG
        const svgDiv = document.createElement("div");
        svgDiv.innerHTML = decodedSvg;

        // 获取原 ECharts 容器的宽度和高度echartslist
        const containerWidth = echartsElement.offsetWidth;
        const containerHeight = echartsElement.offsetHeight;
        console.log();
        // 设置 SVG 的宽度和高度
        const svgElement = svgDiv.querySelector("svg");
        if (svgElement) {
          svgElement.setAttribute("width", containerWidth);
          svgElement.setAttribute("height", containerHeight);

          // 确保 SVG 有命名空间
          if (!svgElement.hasAttribute("xmlns")) {
            svgElement.setAttribute("xmlns", "http://www.w3.org/2000/svg");
          }

          // 嵌入样式到 SVG
          const styleElement = document.createElementNS(
            "http://www.w3.org/2000/svg",
            "style"
          );
          styleElement.textContent = finalStyles;
          svgElement.insertBefore(styleElement, svgElement.firstChild);
        }

        // 替换 ECharts 容器为 SVG 容器
        echartsElement.parentNode.replaceChild(svgDiv, echartsElement);
      }
    }

    // 3. 创建包含样式的完整HTML
    const pageContent = `
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="UTF-8">
            <style>${finalStyles}</style>
          </head>
          <body>
            ${imgdetailsElement.outerHTML}
          </body>
        </html>
      `;

    if (pageContent) {
      const response = await MyHomeworkhtmltopdf({
        ctrID: route.query.CTRID,
        html: pageContent, // 现在包含完整样式
        //   `    <html>
        //    <head>
        //     <meta charset="UTF-8">
        //     <style></style>
        //   </head>
        //   <body>
        //     11
        //   </body>
        // </html>`
      });
      // // 创建一个 Blob 对象，将 HTML 内容存储在其中
      // const blob = new Blob([pageContent], { type: "text/html" });
      // // // 生成一个指向 Blob 对象的临时 URL
      // const url = URL.createObjectURL(blob);

      // // 使用 window.open 打开新窗口
      // window.open(url, "_blank");

      const downloadUrl = `https://www.manfenbeikao.com/${response.url}`;
      window.open(downloadUrl, "_blank");
      pfdspin.value = false;
    }
  } catch (error) {
    console.error("生成PDF出错:", error);
    Message.error("PDF生成失败，请重试");
    pfdspin.value = false;
  }
};
// watch(
//   () => userStore.$state.subjectID,
//   async (newValue, oldValue) => {

//     // videodata.sid = userStore.$state.subjectID;
//     // form.sid = userStore.$state.subjectID;
//     // Id.value = userStore.$state.subjectID;
//     try {
//       if (userStore.$state.subjectID) {

//         if (courselist.value == "1") {

//           // await VideoList();
//         } else {
//           // await getCourseList();
//         }
//         // postcatZsdlist();
//       }
//     } catch (error) {
//       console.error("获取数据出错:", error);
//     }
//   },
//   { immediate: true }
// );
const runturgo = () => {
  router.back();
};
// 定义按钮是否显示的响应式变量
const showButton = ref(false);

// 置顶函数，将所有.arco-layout 元素滚动到顶部
const primarytop = () => {
  const scrollBoxes = document.querySelectorAll(".arco-layout");
  scrollBoxes.forEach((box) => {
    (box as HTMLElement).scrollTo({
      top: 0,
      behavior: "smooth",
    });
  });
};

// 滚动事件处理函数，根据滚动距离控制按钮显示
const handleScroll = (event: Event) => {
  const target = event.target as HTMLElement;
  const scrollTop = target.scrollTop;
  const scrollLeft = target.scrollLeft;
  // 当滚动距离超过 500px 时显示按钮
  showButton.value = scrollTop > 500;
};
onMounted(() => {
  Report();
  // window.addEventListener('scroll', handleScroll);

  const scrollBoxes = document.querySelectorAll(".arco-layout");
  scrollBoxes.forEach((box) => {
    // 添加滚动事件监听器
    box.addEventListener("scroll", handleScroll);
  });
});
// 组件卸载时移除滚动事件监听器
onUnmounted(() => {
  const scrollBoxes = document.querySelectorAll(".arco-layout");
  scrollBoxes.forEach((box) => {
    // 移除滚动事件监听器，防止内存泄漏
    box.removeEventListener("scroll", handleScroll);
  });
});
</script>
<style lang="less" scoped>
.details {
  //   width: 100vw;
  // height: 100%;
  position: relative;
  // overflow: scroll;
}
.returngo {
  position: absolute;
  cursor: pointer;
  left: 0;
  top: -81px;
}
.imgdetails {
  background-image: url("/img/baogao.png");
  background-size: 100% 100%;
  position: relative;
}

.details-p {
  padding: 1.3vw 0 0 1.3vw;
  line-height: 25px;
  font-size: 0.8vw;
  font-weight: 500;
  color: #03305c;
}
.details-img {
  margin: 1.3vw 0 0 1.3vw;
  width: 77px;
  height: 77px;
  // background-color: pink;
  img {
    width: 100%;
    height: 100%;
  }
}
.content-area {
  // height: 1354px;
  margin: 0 2px;
  padding: 0 10vw;
  text-align: center;
  border-radius: 12px;
  background-color: #fff;
}
.content-detsils2 {
  margin-top: 5vw;
  page-break-inside: avoid; /* 防止跨页 */
}
.bottomlist {
  font-weight: 500;
  font-size: 0.8vw;
  padding: 1vw 0;
  color: #8393a3;
  text-align: center;
}
.primary {
  position: fixed;
  bottom: 10%;
  right: 2vw;
  z-index: 999;
  color: #5b8ff9;
  font-size: 2vw;
}
.spinnu {
  text-align: center;
}
</style>
